import Taro,{Component} from "@tarojs/taro"
import styles from './index.module.scss'
import { View, Image, Input, Button } from "@tarojs/components"
import {connect} from '@tarojs/redux'
import FRONT_IMG from '@/assets/img/frontImg.png'
import BACK_IMG from '@/assets/img/backImg.png'
import { AtIcon } from 'taro-ui'
import { sms, captcha, confirmByHome } from '@/api/index'
import { IsMobile } from "@/util/validate"
import { setUrl } from '@/actions/web'

@connect(({home}) => ({
  city: home.city
}), dispatch => ({
  setUrl: (data) => dispatch(setUrl(data))
}))
class Home extends Component {

  config = {
    navigationBarTitleText: '注册签章'
  }

  state = {
    verifyImg: '',
    verify: '',
    mobile: '',
    timeout: 0,
    smsBtnDisabled: false,
    firstImg: FRONT_IMG,
    secondImg: BACK_IMG,
    name: '',
    idCard: '',
    bankCard: '',
    code: ''
  }

  componentWillMount = () => {
    this.getVerify()
  }

  getVerify = async () => {
    let res = await captcha()
    let url = ('data:image/png;base64,' + res).replace(/[\r\n]/g, "")
    this.setState({
      verifyImg: url
    })
  }

  validateMobile = () => {
    const { mobile, verify } = this.state
    if (!mobile) {
      Taro.showToast({title: '未输入手机号！', icon: 'none'})
      return false
    }
    if (!verify) {
      Taro.showToast({title: '未输入图片验证码！', icon: 'none'})
      return false
    }
    if (!IsMobile(mobile)) {
      Taro.showToast({title: '未输入正确手机号！', icon: 'none' })
      return false
    }
    return true
  }

  sendCode = async() => {
    if (!this.validateMobile()) return
    try {
      const { mobile, verify } = this.state
      const { data } = await sms({mobile: mobile, code: verify})
      this.getTimeout()
    } catch(e) {
      Taro.showToast({title: e.message, icon: 'none'})
      this.getVerify()
    }

  }
  getTimeout = () => {
    this.setState({timeout: 30, smsBtnDisabled: true}, () => {
      this.interval = setInterval(() => {
        if (this.state.timeout > 0) {
          this.setState(pre=> ({timeout: pre.timeout-1}))
        } else {
          this.setState({smsBtnDisabled: false})
          clearInterval(this.interval)
        }
      }, 1000)
    })
  }

  chooseImage = async (type) => {
    try{
      const { tempFilePaths, tempFiles } = await Taro.chooseImage({sourceType: ['album'], count: 1})
      Taro.showLoading({title: '图片上传ing...', mask: true})
      const res = await Taro.getFileSystemManager().readFileSync(tempFilePaths[0], 'base64')
      Taro.hideLoading()
      let base64 = 'data:image/jpeg;base64,' + res
      if (type === 'FIRST') {
        this.setState({firstImg: base64})
      } else {
        this.setState({secondImg: base64})
      }
    } catch(e) {
      console.log(e)
    }
  }

  validateArgs = () => {
    const { name, idCard, bankCard, code, firstImg, secondImg } = this.state
    const { city } = this.props
    if (!this.validateMobile()) return false
    if (!name) {
      Taro.showToast({title: '未输入姓名！', icon: 'none'})
      return false
    }
    if (!idCard) {
      Taro.showToast({title: '未输入身份证！', icon: 'none'})
      return false
    }
    if (!bankCard) {
      Taro.showToast({title: '未输入银行卡号！', icon: 'none'})
      return false
    }
    if (!code) {
      Taro.showToast({title: '未输入验证码！', icon: 'none'})
      return false
    }
    if (!city) {
      Taro.showToast({title: '未选择城市！', icon: 'none'})
      return false
    }
    if (firstImg === FRONT_IMG || secondImg === BACK_IMG) {
      Taro.showToast({title: '未上传身份证照片！', icon: 'none'})
      return false
    }
    return true
  }

  confirm = async () => {
    if (!this.validateArgs()) return
    const { name, idCard, bankCard, code, firstImg, secondImg, mobile } = this.state
    const { city } = this.props
    try {
      Taro.showLoading({mask: true, title: '正在加载合同.'})
      const { data } = await confirmByHome({name, idNo: idCard, mobile, code, cardNo: bankCard, region: city, positiveIDPhoto: firstImg, negativeIDPhoto: secondImg})
      Taro.hideLoading()
      this.props.setUrl(data.url)
      Taro.navigateTo({url: `/pages/web/index`})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  render () {
    const { firstImg, secondImg, verifyImg, mobile, verify, smsBtnDisabled, timeout, name, idCard, bankCard, code } = this.state
    const { city } = this.props
    return (
      <View className={styles.wrapper}>
        <View>请上传您的身份证照片</View>
        <View className={styles.imgWrapper}>
          <View className={styles.imgContainer}>
            <Image src={firstImg} className={styles.defaultImg} onClick={() => this.chooseImage('FIRST')}></Image>
          </View>
          <View className={styles.imgContainer}>
            <Image src={secondImg} className={styles.defaultImg} onClick={() => this.chooseImage('SECOND')}></Image>
          </View>
        </View>
        <View className={styles.inputWrapper}>
          <View className={styles.inputContainer}>
            <View className={styles.label}>工作地区</View>
            <Input className={styles.input} value={city} placeholder={'请选择地区'} disabled onClick={() => Taro.navigateTo({url: '/pages/geo/index'})}></Input>
            <View className={styles.right}><AtIcon value={'iconfont iconright'} size={18}></AtIcon></View>
          </View>
          <View className={styles.inputContainer}>
            <View className={styles.label}>真实姓名</View>
            <Input className={styles.input} placeholder={'请填写真实姓名'} value={name} onInput={(e) => this.setState({name: e.detail.value})}></Input>
          </View>
          <View className={styles.inputContainer}>
            <View className={styles.label}>证件号码</View>
            <Input className={styles.input} placeholder={'请填写身份证号码'} value={idCard} onInput={(e) => this.setState({idCard: e.detail.value})}></Input>
          </View>
          <View className={styles.inputContainer}>
            <View className={styles.label}>银行卡号</View>
            <Input className={styles.input} placeholder={'请填写储蓄卡卡号'} value={bankCard} onInput={(e) => this.setState({bankCard: e.detail.value})}></Input>
          </View>
          <View className={styles.inputContainer}>
            <View className={styles.label}>手机号</View>
            <Input className={styles.input} placeholder={'请填写真实的手机号码'} type={'number'} maxLength={11} value={mobile} onInput={(e) => this.setState({mobile: e.detail.value})}></Input>
          </View>
          <View className={styles.inputContainer}>
            <View className={styles.label}>图形验证码</View>
            <Input className={styles.input} placeholder={'验证码'} maxLength={4} value={verify} onInput={(e) => this.setState({verify: e.detail.value})}></Input>
            <Image src={verifyImg} className={`${styles.right} ${styles.verify}`} onClick={() => this.getVerify()}></Image>
          </View>
          <View className={styles.inputContainer}>
            <View className={styles.label}>手机验证码</View>
            <Input className={styles.input} type={'number'} maxLength={6} value={code} onInput={(e) => this.setState({code: e.detail.value})}></Input>
            <Button
              className={`${styles.right} ${styles.sendCode}`}
              plain
              size={'mini'}
              onClick={() => this.sendCode()}
              disabled={smsBtnDisabled}>{timeout > 0 ? `${timeout}s后重新发送`: '发送验证码'}</Button>
          </View>
        </View>
        <Button className={styles.confirm} onClick={() => this.confirm()}>确认提交</Button>
      </View>
    )
  }
}

export default Home
